package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.exception.CatchCustomException;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.common.BCrypt;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDto dto) {
        // 判断 参数
        if (dto==null){
            CatchCustomException.catchs(20003,"参数不合法");
        }
        // 判断 参数是否有空值
        if(StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            CatchCustomException.catchs(20004,"用户名或密码为空");
        }
        // 根据name 查找数据
        WmUser wmUser =  this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName,dto.getName()));

        // 判断  数据库没有该name
        if (wmUser==null){
            CatchCustomException.catchs(20005,"用户名错误");
        }
        // 判断  账号状态
        if (wmUser.getStatus()!=1){
            CatchCustomException.catchs(20006,"账号异常");
        }
        //判断 密码是否正确
        if (!BCrypt.checkpw(dto.getPassword(),wmUser.getPassword())){
            CatchCustomException.catchs(20007,"密码错误");
        }
        // 修改最后登录时间
        wmUser.setLoginTime(new Date());
           updateTime(wmUser);
        // 签发令牌
        String token = AppJwtUtil.getToken(Long.parseLong(wmUser.getId() + ""));
        HashMap<String, Object> hashMap = new HashMap<>();
        wmUser.setPassword("");
        hashMap.put("user",wmUser);
        hashMap.put("token",token);
        return  ResponseResult.okResult(hashMap);
    }

    private void updateTime(WmUser wmUser) {
        this.updateById(wmUser);
    }
}
